<template>
    <!-- 人员管理-报警设置 -->
    <div class="empWarnsetting">
        <Tabs value="name1" @on-click="getTabType">
            <TabPane label="安全帽报警" name="name1">
                <div class="search">
                    <el-button :type="warnList.length ===0?'info':'primary'" @click="updateRow(0)" size="small" plain :disabled="warnList.length ===0 || !btnList.includes('emp/warnSetting/recept')">管理消息接收人</el-button>
                </div>
                <div class="table">
                    <el-table :data="tableData" :stripe="true" @select="listSelectOne" @select-all="listSelectALL">
                        <el-table-column type="selection" width="55" align="center"></el-table-column>
                        <el-table-column prop="name" label="报警类型" width="200px"></el-table-column>
                        <!-- <el-table-column label="短信接收">
                            <template slot-scope="scope">
                                <span v-if="scope.row.msgChannelList.includes(4)">√</span>
                                <span v-else>x</span>
                            </template>
                        </el-table-column> -->
                        <el-table-column label="APP接收">
                            <template slot-scope="scope">
                                <span v-if="scope.row.msgChannelList.includes(1)">√</span>
                                <span v-else>x</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="后台接收">
                            <template slot-scope="scope">
                                <span v-if="scope.row.msgChannelList.includes(3)">√</span>
                                <span v-else>x</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="生效时间">
                            <template slot-scope="scope">
                                <div v-if="scope.row.timeList.length > 0">
                                    <p v-for="(val, i) in scope.row.timeList" :key="i">
                                        <span>{{ val.startTime }}</span> <span>--</span>
                                        <span>{{ val.endTime }}</span>
                                    </p>
                                </div>
                                <div v-else>
                                    <span>00:00</span> <span>--</span> <span>23:59</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="消息接收人" prop="nickName" width="250px"></el-table-column>
                        <el-table-column label="状态" prop="nickName">
                            <template slot-scope="scope">
                                <el-tag type="success" size="small" v-if="scope.row.enableFlag == 1">启用</el-tag>
                                <el-tag type="error" size="small" v-if="scope.row.enableFlag == 0">禁用</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="170px" fixed="right" align="center">
                            <template slot-scope="scope">
                                <el-button @click.native.prevent="enable(1,scope.$index, tableData)" type="text" size="small" v-if="scope.row.enableFlag == 0" :disabled="!btnList.includes('emp/warnSetting/hatForbidden')">启用</el-button>
                                <el-button @click.native.prevent="enable(0,scope.$index, tableData)" type="text" size="small" v-if="scope.row.enableFlag == 1" :disabled="!btnList.includes('emp/warnSetting/hatForbidden')">禁用</el-button>
                                <el-button @click.native.prevent="addTime(scope.$index, tableData)" type="text" size="small" :disabled="!btnList.includes('emp/warnSetting/time')">生效时间</el-button>
                                <el-button @click.native.prevent="updateRow(1, scope.$index, tableData)" type="text" size="small" :disabled="!btnList.includes('emp/warnSetting/hatEdit')">编辑</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="clearfix" v-show="tableData.length > 0">
                    <div class="float-right">
                        <Page v-if="totalCount" style="margin: 20px 0;text-align: right;" :current.sync="current" :total="totalCount" :page-size="pageSize" show-elevator show-total @on-change="pageChange"></Page>
                    </div>
                </div>
            </TabPane>
            <TabPane label="系统报警" name="name2">
                <div class="search">
                    <el-button type="primary" @click="updateRuleRow(0)" size="small" plain :disabled="!btnList.includes('emp/warnSetting/add')">+报警类型</el-button>
                </div>
                <div class="table">
                    <el-table :data="tableData" style="width: 100%" :stripe="true">
                        <el-table-column prop="name" label="报警类型" width="200px"></el-table-column>
                        <el-table-column prop="ruleType" label="报警类型">
                            <template slot-scope="scope">
                                <span v-if="scope.row.ruleType == 201">出区域报警</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="machCode" label="报警规则">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" v-show="scope.row.ruleType == 201" @click="getGSPDetails(scope.$index, tableData)">查看详情</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="生效时间">
                            <template slot-scope="scope">
                                <div v-if="scope.row.timeList.length > 0">
                                    <p v-for="(val, i) in scope.row.timeList" :key="i">
                                        <span>{{ val.startTime }}</span>
                                        <span>--</span>
                                        <span>{{ val.endTime }}</span>
                                    </p>
                                </div>
                                <div v-else>
                                    <span>00:00</span>
                                    <span>--</span>
                                    <span>23:59</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="消息接收人" prop="nickName" width="300px"></el-table-column>
                        <el-table-column label="状态" prop="nickName">
                            <template slot-scope="scope">
                                <el-tag type="success" size="small" v-if="scope.row.enableFlag == 1">启用</el-tag>
                                <el-tag type="info" size="small" v-if="scope.row.enableFlag == 0">禁用</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="350px" fixed="right" align="center">
                            <template slot-scope="scope">
                                <el-button @click.native.prevent="updateRuleRow(1, scope.$index, tableData)" type="text" size="small" :disabled="!btnList.includes('emp/warnSetting/sysEdit')">编辑</el-button>
                                <el-button @click.native.prevent="addEmp(scope.$index, tableData)" type="text" size="small" :disabled="!btnList.includes('emp/warnSetting/sysemp')">报警人员</el-button>
                                <el-button @click.native.prevent="enable(1,scope.$index, tableData)" type="text" size="small" v-if="scope.row.enableFlag == 0" :disabled="!btnList.includes('emp/warnSetting/sysForbidden')">启用</el-button>
                                <el-button @click.native.prevent="enable(0,scope.$index, tableData)" type="text" size="small" v-if="scope.row.enableFlag == 1" :disabled="!btnList.includes('emp/warnSetting/sysForbidden')">禁用</el-button>
                                <el-button @click.native.prevent="addTime(scope.$index, tableData)" type="text" size="small" :disabled="!btnList.includes('emp/warnSetting/systime')">生效时间</el-button>
                                <el-button @click.native.prevent = "updateRow(1, scope.$index, tableData)" type = "text" size = "small" :disabled="!btnList.includes('emp/warnSetting/sysRecept')">报警接收人</el-button >
                                <el-button @click.native.prevent="remove(scope.$index, tableData)" type="text" style="color:red" size="small" :disabled="!btnList.includes('emp/warnSetting/sysDelete')">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="clearfix" v-show="tableData.length > 0">
                    <div class="float-right">
                        <Page v-if="totalCount" style="margin: 20px 0;text-align: right;" :current.sync="current" :total="totalCount" :page-size="pageSize" show-elevator show-total @on-change="pageChange"></Page>
                    </div>
                </div>
            </TabPane>
        </Tabs>

        <Modal v-model="updateModal" :title="isAdd ? '管理消息接收人' : '编辑消息接收人'" width="660px;" :mask-closable="false">
            <div class="ask">
                <span>通知方式:</span>
                <el-checkbox-group v-model="checkList">
                    <!-- <el-checkbox label="短信通知"></el-checkbox> -->
                    <el-checkbox label="APP通知"></el-checkbox>
                    <el-checkbox label="后台通知"></el-checkbox>
                </el-checkbox-group>
            </div>
            <el-transfer v-model="list" :data="msgList" :titles="['所有接收人员', '已有接收人员']"></el-transfer>
            <div slot="footer">
                <el-button @click="cancel(0)" type="info" size="small" plain>取消</el-button>
                <el-button @click="submitAll" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <Modal v-model="timeModal" title="生效时间设置" width="400px;" :mask-closable="false">
            <div class="warn">
                <div class="list">
                    <span>生效时间:</span>
                    <el-button style="margin-left:10px;" @click="addTimeRow" :disabled="timeList.length == 3" :type="timeList.length == 3?'info':'primary'" size="small" plain>添加</el-button>
                </div>
                <div class="list">
                    <div class="item1">
                        <div v-for="(val, i) in timeList" :key="i" style="margin-bottom:10px">
                            <TimePicker format="HH:mm" type="timerange" placement="bottom-end" placeholder="请选择时间" style="width: 168px" v-model="timeList[i].time" :clearable="false"></TimePicker>
                            <el-button @click="removeTimeRow(i)" :disabled="timeList.length == 1" :type="timeList.length == 1?'info':'danger'" size="small" plain>删除</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div slot="footer">
                <el-button @click="cancel(1)" type="info" size="small" plain>取消</el-button>
                <el-button type="primary" @click="sumbitTime" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <!--新增编辑系统报警-->
        <Modal v-model="updateRuleModal" :title="isAdd ? '添加报警' : '编辑报警'" width="660px;" :mask-closable="false">
            <div class="ruleBox">
                <div class="left">
                    <div class="title">
                        <h2>
                            <span>报警类型</span>
                        </h2>
                    </div>
                    <div class="infoBox" style="margin:10px auto;width:150px">
                         <RadioGroup v-model="ruleType" vertical >
                            <Radio :label="item.id" v-for="(item,index) in ruleTypeList" :key="index" :disabled = !isAdd>
                                <Icon type="social-apple"></Icon>
                                <span style="color:#181818; font-family: MicrosoftYaHei;font-size:14px;">{{item.name}}</span>
                            </Radio>
                        </RadioGroup>
                    </div>
                </div>
                <div class="right">
                    <div class="title" style="margin-left: 15px">
                        <h2>
                            <span>报警规则</span>
                        </h2>
                    </div>
                    <div class="infoBox" style="margin:20px auto; width: 300px;">
                        <div class="item" style="width:300px;">
                            <span class="tip">*</span>
                            <span class="span">报警名称:</span>
                            <Input  v-model="ruleName" :maxlength="count" placeholder="请输入报警名称" style="width:200px" clearable />
                        </div>
                    </div>
                    <div class="infoBox">
                        <div class="item" style="width:300px;">
                            <span class="tip" style="color:red;">*</span>
                            <span class="span">报警规则</span>
                        </div>
                        <div class="item" style="width:250px;">
                            <RadioGroup v-model="radio">
                                <Radio label="0">自定义新建</Radio>
                                <!-- <Radio label="1">电子围栏</Radio>-->
                            </RadioGroup>
                        </div>
                        <div class="item"  style="width:250px;">
                            <el-button type="primary" @click="getGps" size="small" style="background:#1891FF;">
                                <span v-if="type == ''" style="color:#FFF;">点击设置区域范围</span>
                                <span v-if="type != ''" style="color:#FFF;">点击查看范围区域</span>
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div slot="footer">
                <el-button @click="cancel(3)" type="info" size="small" plain>取消</el-button>
                <el-button @click="submitRuleAll" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <!--电子围栏-->
        <Modal v-model="GPSModal" title="设置范围区域" width="1300px" :mask-closable="false" >
            <div class="msg">
                <div class="fence">
                    <div id="container" class="container" style="border:1px solid #1891FF;"></div>
                    <div class="searchAddress">
                         <Input search enter-button placeholder="请输入准确的项目地址"  style="width:300px"  @on-search="searchAddress" v-model="address" clearable />
                    </div>
                </div>
                <div class="right">
                <div class="top">
                    <input type="radio" name="func" value="polygon" />
                    <span class="input-text" style="width:50px;">画多边形</span>
                    <input type="radio" name="func" value="circle" />
                    <span class="input-text">画圆</span>
                </div>
                <div class="isShow" v-show="sub == 1">
                    点击鼠标“左键”开始绘图，点击鼠标“右键”或“双击左键”结束绘图
                </div>
                <div class="center">
                    <p v-show="sub !== 0">
                        <span>经度</span>
                        <span>纬度</span>
                    </p>
                    <div v-for="(item,index) in polygonPointList" :key="index" v-show="sub == 1">
                        <Input v-model="item.lng" placeholder="请输入经度" style="width:80px" clearable />
                        <Input v-model="item.lat" placeholder="请输入纬度" style="width:80px ;margin-right:10px;margin-left:10px;" clearable />
                        <el-button @click="removeRow(index)" :disabled="polygonPointList.length == 3" :type="polygonPointList.length == 3?'info':'danger'" size="small" plain>删除</el-button>
                    </div>
                    <div v-show="sub == 2">
                        <Input v-model="radius" placeholder="请输入半径" style="width:200px" clearable />
                    </div>
                    <div v-show="sub == 2">
                        <Input v-model="centerPoint.lng" placeholder="请输入半径" style="width:80px" clearable />
                        <Input v-model="centerPoint.lat" placeholder="请输入半径" style="width:80px;margin-left:10px" clearable />
                    </div>
                    <p v-if="sub !== 0">
                        <el-button type="primary" @click="addRow" style="margin-right:20px" size="small" plain v-if="sub == 1">加点</el-button>
                        <el-button type="primary" @click="drawArea" style="margin-right:20px" size="small" plain>绘制</el-button>
                    </p>
                    </div>
                </div>
            </div>
            <div slot="footer">
                <el-button @click="cancel(2)"  type="info" size="small">取消</el-button>
                <el-button @click="sumbitGps" type="primary"  size="small"  v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <Modal v-model="gspDetailsModal" width="1000px" title="电子围栏报警区域" :mask-closable="false" :footer-hide="true" >
            <div class="msg">
                <div style="width:900px;height:500px;margin:20px auto;">
                    <div id="fenceMap" class="fenceMap"></div>
                </div>
            </div>
        </Modal>

        <Modal v-model="delModal" title="删除" width="360px;" :mask-closable="false">
            <div style="margin:10px">确定要删除这条数据吗？</div>
            <div slot="footer">
                <el-button @click="cancel(4)" type="info" size="small" plain>取消</el-button>
                <el-button type="primary" @click="del" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <Modal v-model="empObjModal" title="报警人员设置" width="660px;" :mask-closable="false">
            <el-transfer v-model="empList" :data="msgEmpList" filterable :filter-method="filterMethod" ref="myTransfer" filter-placeholder="请输入人员名称，工种" :titles="['所有人员', '已有人员']">
            </el-transfer>
            <div slot="footer">
                <el-button @click="cancel(5)" type="info" size="small" plain>取消</el-button>
                <el-button @click="subMitEmp" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>
    </div>
</template>
<script>
import {
    getEmpSettingList,
    getEmpUseAdd,
    getMsgRuleAvailableUsers,
    getEmpSetTime,
    getEmpSettingEnable,
    getEmpWarnSettingAdd,
    getEmpWarnSettingEdit,
    getEmpSettingDel,
    getEmpAllObjectEmp,
    getEmpObjectList,
    getEmpObjectAdd,
} from "@/api/api.js";
export default {
    data() {
        return {
            deptId: "",
            list: [],
            msgList: [],
            tableData: [],
            current: 1,
            pageSize: 10,
            pageNum: 1,
            totalCount: 0,
            isAdd: false,
            updateModal: false,
            count: 16,
            updataID: "",
            warnList: [],
            checkList: [],
            TZList: [
                {
                    id: 1,
                    name: "APP通知",
                },
                {
                    id: 2,
                    name: "公众号通知",
                },
                {
                    id: 3,
                    name: "后台通知",
                },
                {
                    id: 4,
                    name: "短信通知",
                },
            ],
            timeList: [
                {
                    time: [],
                },
            ],
            timeId: "",
            timeModal: false,
            warnType: 1,
            updateRuleModal: false,
            ruleTypeList: [
                {
                    id: 201,
                    name: "出区域"
                },
            ],
            ruleType: 201,
            ruleName: "",
            type: "",
            radio: '0',
            GPSModal: false,
            sub: '',
            polygonPointList: [],
            radius: "",
            centerPoint: {},
            address: "",
            gspDetailsModal: false,
            fenceObj: {},
            cover: "",
            ruleId: "",
            delModal: false,
            empObjModal: false,
            empList: [],
            msgEmpList: [],
            btnList:[],
        };
    },
    computed: {
        porjectObject() {
            return this.$store.state.porjectObject;
        },
    },
    watch: {
        porjectObject(val, oldVal) {
            if (val.deptId != oldVal.deptId) {
                this.deptId = val.deptId;
                // this.warnType = 1;
                this.pageSize = 10;
                this.pageNum = 1;
                this.getList();
            }
        },
    },
    methods: {
        searchAddress(){
            if(this.address == "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请输入地址"
                });
                return;
            }
            var _that =this;
            AMap.service("AMap.Geocoder", function() {
                var geocoder = new AMap.Geocoder({
                    city: "", //城市设为北京，默认：“全国”
                });
                var marker = new AMap.Marker();
                geocoder.getLocation(_that.address, function(status, result) {
                    if (status === 'complete'&&result.geocodes.length) {
                        var lnglat = result.geocodes[0].location
                        marker.setPosition(lnglat);
                        _that.fenceMap.setFitView(marker);
                    }else{
                        _that.$Message.warning('根据地址查询位置失败');
                        // log.error('根据地址查询位置失败');
                    }
                });
            });

        },
        filterMethod(query, item) {
            return ( item.empName.indexOf(query) > -1 || item.workTypeName.indexOf(query) > -1);
        },
        subMitEmp() {
            var arr = [];
            for (let i in this.empList) {
                for (let j in this.msgEmpList) {
                    if (this.empList[i] == this.msgEmpList[j].key) {
                        arr.push(this.msgEmpList[j].empId);
                    }
                }
            }
            arr = [...new Set(arr )];
            let params = {
                ruleId: this.ruleId,
                empIdList: arr
            };
            getEmpObjectAdd(params)
                .then(res => {
                    if (res.code == 200) {
                        this.empObjModal = false;
                        this.$Message.success("操作成功");
                        this.pageNum = 1;
                        this.getList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        addEmp(index, rows) {
            this.$refs.myTransfer.$children["0"]._data.query = "";
            this.$refs.myTransfer.$children["3"]._data.query = "";
            let params = {
                ruleId: rows[index].ruleId,
            };
            getEmpObjectList(params).then(res => {
                if (res.code == 200) {
                    this.getAddObjList(rows[index].ruleId, res.data.list);
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error);
            });
            this.ruleId = rows[index].ruleId;
            this.empObjModal = true;
        },
        getAddObjList(id, arr) {
            this.msgEmpList = [];
            let params = {
                ruleId: id,
            };
            getEmpAllObjectEmp(params).then(res => {
                if (res.code == 200) {
                    let x = res.data.list;
                    for (let i in arr) {
                        x.push(arr[i]);
                    }
                    for (var i = 0; i < x.length; i++) {
                        for (var j = i + 1; j < x.length; j++) {
                            if (x[i].empId == x[j].empId) {
                                //第一个等同于第二个，splice方法删除第二个
                                x.splice(j, 1);
                                j--;
                            }
                        }
                    }
                    for (let i in x) {
                        this.msgEmpList.push({
                            key: i.toString(),
                            label: x[i].empName + '-' + x[i].workTypeName ,
                            empId: x[i].empId,
                            empName: x[i].empName,
                            workTypeName: x[i].workTypeName || '' ,
                        });
                    }
                    this.empList = [];
                    for (var i = 0; i < arr.length; i++) {
                        for (var j = 0; j < this.msgEmpList.length; j++) {
                            if (arr[i].empId == this.msgEmpList[j].empId) {
                                this.empList.push(j.toString());
                            }
                        }
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error);
            });
        },
        removeRow(index) {
            this.polygonPointList.splice(index, 1);
        },
        //查看电子围栏报警详情
        getGSPDetails(index, rows) {
            this.gspDetailsModal = true;
            if (rows[index].type == 1) {
                //计算多边形中心点的坐标;
                var polygonPointList = rows[index].polygonPointList;
                var a = [];
                var b = [];
                var path = [];
                for (let i in polygonPointList) {
                    a.push(polygonPointList[i].lat);
                    b.push(polygonPointList[i].lng);
                    //多边形的坐标点
                    let x = [polygonPointList[i].lng, polygonPointList[i].lat];
                    path.push(x);
                }
                let latSum = 0;
                for (let i in a) {
                    latSum += a[i];
                }
                var lat = latSum / a.length;
                let lngSum = 0;
                for (let i in b) {
                    lngSum += b[i];
                }
                var lng = lngSum / b.length;
                var polygon = new AMap.Polygon({
                    path: path,
                    strokeColor: "#ff00ff",
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    fillColor: "#ff00ff",
                    zIndex: 50
                });
            } else if (rows[index].type == 2) {
                var lat = rows[index].centerPoint.lat;
                var lng = rows[index].centerPoint.lng;
                var radius = rows[index].radius;
                var circle = new AMap.Circle({
                    center: [lng, lat],
                    radius: radius, //半径
                    borderWeight: 3,
                    strokeColor: "#ff00ff",
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    strokeStyle: "dashed",
                    strokeDasharray: [10, 10],
                    // 线样式还支持 'dashed'
                    fillColor: "#ff00ff",
                    zIndex: 50
                });
            }
            var map = new AMap.Map("fenceMap", {
                resizeEnable: true, //是否监控地图容器尺寸变化
                zoom: 14, //初始化地图层级
                center: [lng, lat], //初始化地图中心点
                layers: [
                    // 卫星
                    new AMap.TileLayer.Satellite(),
                    // 路网
                    new AMap.TileLayer.RoadNet()
                ]
            });
            // 构造官方卫星、路网图层
            var satelliteLayer = new AMap.TileLayer.Satellite();
            var roadNetLayer = new AMap.TileLayer.RoadNet();

            // 批量添加图层
            map.add([satelliteLayer, roadNetLayer]);
            if (rows[index].type == 1) {
                map.add(polygon);
                // 缩放地图到合适的视野级别
                map.setFitView([polygon]);
            } else if (rows[index].type == 2) {
                circle.setMap(map);
                // 缩放地图到合适的视野级别
                map.setFitView([circle]);
            }
        },
        drawArea() {
            if (this.sub == 1) {
                this.fenceMap.clearMap();
                var path = [];
                for (let i = 0; i < this.polygonPointList.length; i++) {
                    if (
                        this.polygonPointList[i].lat == "" ||
                        this.polygonPointList[i].lng == ""
                    ) {
                        this.$Modal.warning({
                            title: "您有必填字段",
                            content: "经纬度不能为空",
                        });
                    }
                    //多边形的坐标点
                    let x = [this.polygonPointList[i].lng, this.polygonPointList[i].lat];
                    path.push(x);
                }
                this.cover = new AMap.Polygon({
                    path: path,
                    strokeColor: "#ff00ff",
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    fillColor: "#ff00ff",
                    zIndex: 50,
                });
                this.cover.setMap(this.fenceMap);
            } else if (this.sub == 2) {
                if (this.radius == "") {
                    this.$Modal.warning({
                        title: "您有必填字段",
                        content: "半径不能为空",
                    });
                }
                if (this.centerPoint.lng == "" || this.centerPoint.lat == "") {
                    this.$Modal.warning({
                        title: "您有必填字段",
                        content: "经纬度不能为空",
                    });
                }
                this.fenceMap.clearMap();
                this.cover = new AMap.Circle({
                    center: [this.centerPoint.lng, this.centerPoint.lat],
                    radius: this.radius, //半径
                    borderWeight: 3,
                    strokeColor: "#ff00ff",
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    strokeStyle: "dashed",
                    strokeDasharray: [10, 10],
                    // 线样式还支持 'dashed'
                    fillColor: "#ff00ff",
                    zIndex: 50,
                });
                this.cover.setMap(this.fenceMap);
                // 缩放地图到合适的视野级别
                this.fenceMap.setFitView(this.cover);
            }
        },
        addRow() {
            let obj = {
                lat: "",
                lng: "",
            };
            this.polygonPointList.push(obj);
        },
        sumbitGps() {
            if (this.sub == 1) {
                for (let i = 0; i < this.polygonPointList.length; i++) {
                    if (this.polygonPointList[i].lat == "" || this.polygonPointList[i].lng == "") {
                        this.$Modal.warning({
                            title: "您有必填字段",
                            content: "经纬度不能为空",
                        });
                        return;
                    }
                }
            }
            this.type = this.sub;
            this.GPSModal = false;
        },
        getGps() {
            if(this.sub === 0) {
                this.sub = this.fenceObj.type;
            }
            var _that = this;
            _that.GPSModal = true;
            if (_that.type == 1) {
                var polygonPointList = _that.polygonPointList;
                var a = [];
                var b = [];
                var path = [];
                for (let i in polygonPointList) {
                    a.push(polygonPointList[i].lat);
                    b.push(polygonPointList[i].lng);
                    //多边形的坐标点
                    let x = [polygonPointList[i].lng, polygonPointList[i].lat];
                    path.push(x);
                }
                let latSum = 0;
                for (let i in a) {
                    latSum += a[i];
                }
                var lat = latSum / a.length;
                let lngSum = 0;
                for (let i in b) {
                    lngSum += b[i];
                }
                var lng = lngSum / b.length;
                _that.cover = new AMap.Polygon({
                    path: path,
                    strokeColor: "#ff00ff",
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    fillColor: "#ff00ff",
                    zIndex: 50
                });
                _that.fenceMap = new AMap.Map("container", {
                    zoom: 14,
                    center: [lng, lat]
                });
            } else if (_that.type == 2) {
                var lat = _that.centerPoint.lat;
                var lng = _that.centerPoint.lng;
                var radius = _that.radius;
                _that.cover = new AMap.Circle({
                    center: [lng, lat],
                    radius: radius, //半径
                    borderWeight: 3,
                    strokeColor: "#ff00ff",
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    strokeStyle: "dashed",
                    strokeDasharray: [10, 10],
                    // 线样式还支持 'dashed'
                    fillColor: "#ff00ff",
                    zIndex: 50
                });
                _that.fenceMap = new AMap.Map("container", {
                    zoom: 14,
                    center: [lng, lat]
                });
            } else {
                if (_that.lng == undefined) {
                    _that.fenceMap = new AMap.Map("container", {
                        zoom: 14
                    });
                } else {
                    _that.fenceMap = new AMap.Map("container", {
                        zoom: 14,
                        center: [_that.lng, _that.lat]
                    });
                }
            }
            var radios = document.getElementsByName("func");
            //清空input的选择
            for(var i = 0; i < radios.length; i += 1){
                radios[i].checked="";
            }
            var mouseTool = new AMap.MouseTool(_that.fenceMap);
            // 构造官方卫星、路网图层
            var satelliteLayer = new AMap.TileLayer.Satellite();
            var roadNetLayer = new AMap.TileLayer.RoadNet();
            //添加图层
            _that.fenceMap.add([satelliteLayer, roadNetLayer]);
            if (_that.type == 1) {
                _that.fenceMap.add(_that.cover);
                // 缩放地图到合适的视野级别
                _that.fenceMap.setFitView([_that.cover]);
            } else if (_that.type == 2) {
                // circle.setMap(map);
                _that.fenceMap.add(_that.cover);
                // 缩放地图到合适的视野级别
                _that.fenceMap.setFitView([_that.cover]);
            }
            var arr = [];
            mouseTool.on("draw", function(e) {
                if (_that.type != "") {
                    _that.fenceMap.remove(_that.cover);
                }
                if (arr.length >= 1) {
                    _that.fenceMap.remove(arr);
                    arr.push(e.obj);
                } else {
                    arr.push(e.obj);
                }
                if (arr.length > 0) {
                    //记录多边形的点
                    if (arr[arr.length - 1].CLASS_NAME == "AMap.Polygon") {
                        var x= [];
                        let pathArr = arr[arr.length - 1].Ce ? arr[arr.length - 1].Ce.path : arr[arr.length - 1].De.path
                        for ( let i = 0; i < pathArr.length;  i++ ) {
                            let obj = {
                                lng: pathArr[i].lng,
                                lat: pathArr[i].lat,
                            };
                            x.push(obj);
                        }
                        _that.polygonPointList = x;
                    }
                    if (arr[arr.length - 1].CLASS_NAME == "AMap.Circle") {
                        //记录圆形的圆心和半径
                        let pathCir = arr[arr.length - 1].Ce ? arr[arr.length - 1].Ce : arr[arr.length - 1].De
                        _that.radius = pathCir.radius;
                        _that.centerPoint = pathCir.center;
                    }
                }
            });
            _that.overlays = arr;
            function draw(type) {
                switch (type) {
                    case "polygon": {
                        mouseTool.polygon({
                            fillColor: "#ff00ff",
                            strokeColor: "#ff00ff",
                            strokeWeight: 6,
                            strokeOpacity: 0.2,
                            fillOpacity: 0.4,
                            //同Polygon的Option设置
                        });
                        break;
                    }
                    case "circle": {
                        mouseTool.circle({
                            fillColor: "#ff00ff",
                            strokeColor: "#ff00ff",
                            borderWeight: 3,
                            strokeWeight: 6,
                            strokeOpacity: 0.2,
                            fillOpacity: 0.4,
                            strokeStyle: "dashed",
                            strokeDasharray: [10, 10],
                            //同Circle的Option设置
                        });
                        break;
                    }
                }
            }
            for (var i = 0; i < radios.length; i += 1) {
                radios[i].onchange = function (e) {
                    draw(e.target.value);
                    if (e.target.value == "polygon") {
                        _that.sub = 1;
                    } else if (e.target.value == "circle") {
                        _that.sub = 2;
                    } else {
                        _that.sub = 0;
                    }
                };
            }
        },
        submitRuleAll() {
            if (this.ruleName == "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "报警名称不能为空"
                });
                return;
            }
            if (this.type == "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请选择电子围栏"
                });
                return;
            }
            if(this.isAdd) {
                let params = {
                    ruleType: this.ruleType,
                    name: this.ruleName,
                    type: this.type,
                    polygonPointList: this.polygonPointList,
                    centerPoint: {
                        lng: this.centerPoint.lng,
                        lat: this.centerPoint.lat
                    },
                    deptId: this.deptId,
                    radius: this.radius
                }
                console.log(params)
                getEmpWarnSettingAdd(params).then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.updateRuleModal = false;
                        this.current = 1;
                        this.pageNum = 1;
                        this.getList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                }).catch(error => {
                    console.log(error)
                })
            } else {
                let params ={
                    ruleType: this.ruleType,
                    name: this.ruleName,
                    type: this.type,
                    polygonPointList: this.polygonPointList,
                    centerPoint: {
                        lng: this.centerPoint.lng,
                        lat: this.centerPoint.lat
                    },
                    ruleId: this.ruleId,
                    radius: this.radius
                }
                getEmpWarnSettingEdit(params).then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.updateRuleModal = false;
                        this.current = 1;
                        this.pageNum = 1;
                        this.getList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                }).catch(error => {
                    consolo.log(error)
                })
            }
        },
        getTabType(name){
            if (name == 'name1') {
                this.warnType = 1;
            } else if (name == 'name2') {
                this.warnType = 2;
            }
            this.pageNum = 1;
            this.pageSize = 10;
            this.getList();
        },
        updateRuleRow(type, index, rows) {
            this.updateRuleModal = true;
            let arr = [
                {
                    lat: "",
                    lng: "",
                },
                {
                    lat: "",
                    lng: "",
                },
                {
                    lat: "",
                    lng: "",
                },
            ]
            if (type == 0) {
                this.isAdd = true;
                this.type = "";
                this.polygonPointList = arr;
                this.radius = "";
                this.centerPoint = {};
                this.ruleName = "";
                this.fenceObj = {};
            } else if (type == 1) {
                this.isAdd = false;
                this.fenceObj = rows[index];
                this.type = rows[index].type;
                this.ruleName = rows[index].name
                this.polygonPointList = rows[index].polygonPointList == undefined ? arr : rows[index].polygonPointList;
                this.centerPoint = rows[index].centerPoint == undefined ? {} : rows[index].centerPoint;
                this.radius = rows[index].radius;
                this.ruleId = rows[index].ruleId;
            }
        },
        //删除
        remove(index, rows) {
            this.ruleId = rows[index].ruleId;
            this.delModal = true;
        },
        del(){
            getEmpSettingDel(this.ruleId).then(res=>{
                if(res.code == 200) {
                    this.$Message.success("操作成功");
                    this.delModal = false;
                    this.current = 1;
                    this.pageNum = 1;
                    this.getList();
                }
            }).catch(error=>{
                console.log(error)
            })
        },
        enable(type,index,rows){
            let params ={
                 ruleId:rows[index].ruleId,
                 enableFlag:type
            }
            getEmpSettingEnable(params).then(res=>{
                if(res.code == 200) {
                    this.$Message.success("操作成功");
                    this.pageNum = 1;
                    this.getList();
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error=>{
                consle.log(error)
            })
        },
        getList() {
            this.tableData = [];
            let params = {
                deptId: this.deptId,
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                warnType: this.warnType
            };
            getEmpSettingList(params)
                .then((res) => {
                    if (res.code == 200) {
                        this.tableData = res.data.list;
                        for (let i in this.tableData) {
                            let operEmpNameStr = [];
                            for (let j in this.tableData[i].userList) {
                                operEmpNameStr.push(this.tableData[i].userList[j].nickName);
                                this.tableData[i]["nickName"] = operEmpNameStr.join(",");
                            }
                        }
                        this.totalCount = res.data.total;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        pageChange(index) {
            this.pageNum = index;
            this.getList();
        },
        getUserList(arr) {
            this.msgList = [];
            let params = {
                deptId: this.deptId,
            };
            getMsgRuleAvailableUsers(params)
                .then((res) => {
                    if (res.code == 200) {
                        let list = res.data.list;
                        let newObj = {};
                        list = list.reduce((preVal, curVal) => {
                            newObj[curVal.userId] ? '' : newObj[curVal.userId] = preVal.push(curVal);
                            return preVal
                        }, []);
                        for (let i in list) {
                            this.msgList.push({
                                key: i.toString(),
                                label: list[i].nickName + list[i].phone,
                                userId: list[i].userId,
                                phone: list[i].phone,
                                username: list[i].username,
                                nickName: list[i].nickName,
                            });
                        }
                        if (!this.isAdd) {
                            this.list = [];
                            for (var i = 0; i < arr.length; i++) {
                                for (var j = 0; j < this.msgList.length; j++) {
                                    if (arr[i].userId == this.msgList[j].userId) {
                                        this.list.push(j.toString());
                                    }
                                }
                            }
                        }
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        updateRow(type, index, rows) {
            if (type == 0) {
                this.isAdd = true;
                this.checkList = [];
                this.list = [];
                this.getUserList();
            } else if (type == 1) {
                this.isAdd = false;
                this.checkList = [];
                for (let i in rows[index].msgChannelList) {
                    for (let j in this.TZList) {
                        if (rows[index].msgChannelList[i] == this.TZList[j].id) {
                            this.checkList.push(this.TZList[j].name);
                        }
                    }
                }
                this.getUserList(rows[index].userList);
                this.updataID = rows[index].ruleId;
            }
            this.updateModal = true;
        },
        submitAll() {
            var arr = [];
            for (let i in this.list) {
                for (let j in this.msgList) {
                    if (this.list[i] == this.msgList[j].key) {
                        arr.push({
                            userId: this.msgList[j].userId,
                            nickName: this.msgList[j].nickName,
                            phone: this.msgList[j].phone,
                        });
                    }
                }
            }
            let msgChannelList = [];
            if(this.checkList.length===0){
                this.$Message.warning("请选择通知方式");
                return
            }
            for (let i in this.checkList) {
                for (let j in this.TZList) {
                    if (this.checkList[i] == this.TZList[j].name) {
                        msgChannelList.push(this.TZList[j].id);
                    }
                }
            }
            let params;
            let idList = [];
            if (this.isAdd) {
                this.warnList.forEach((i) => {
                    idList.push(i.ruleId);
                });
                params = {
                    ruleIdList: idList,
                    userList: arr,
                    msgChannelList: msgChannelList,
                };
            } else {
                params = {
                    ruleIdList: [this.updataID],
                    userList: arr,
                    msgChannelList: msgChannelList,
                };
            }
            getEmpUseAdd(params)
                .then((res) => {
                    if (res.code == 200) {
                        this.updateModal = false;
                        this.$Message.success("操作成功");
                        this.pageNum = 1;
                        this.getList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        cancel(type) {
            if (type == 0) {
                this.updateModal = false;
            } else if (type == 1) {
                this.timeModal = false;
            } else if (type == 2) {
                this.sub = 0;
                //每次绘制之前清除之前的绘制的图形
                this.fenceMap.clearMap();
                this.polygonPointList = [
                    {
                        lat: "",
                        lng: "",
                    },
                    {
                        lat: "",
                        lng: "",
                    },
                    {
                        lat: "",
                        lng: "",
                    },
                ];
                this.centerPoint = {};
                this.radius = "";
                this.GPSModal = false;
            } else if (type == 3) {
                this.updateRuleModal = false;
            } else if (type == 4) {
                this.delModal = false;
            } else if (type == 5) {
                this.empObjModal = false
            }
        },
        //多选
        listSelectOne(selection) {
            this.warnList = selection;
        },
        //全选
        listSelectALL(selection) {
            this.warnList = selection;
        },
        addTime(index, rows) {
            this.timeId = rows[index].ruleId;
            this.timeModal = true;
            if (rows[index].timeList.length != 0) {
                this.timeList = [];
                rows[index].timeList.forEach((i) => {
                    let obj = {
                        time: [i.startTime, i.endTime],
                    };
                    this.timeList.push(obj);
                });
            } else {
                this.timeList = [
                    {
                        time: [],
                    },
                ];
            }
        },
        addTimeRow() {
            let obj = {
                time: [],
            };
            this.timeList.push(obj);
        },
        removeTimeRow(i) {
            this.timeList.splice(i, 1);
        },
        sumbitTime() {
            for (let i in this.timeList) {
                //判断是否存在空的时间
                if (this.timeList[i].time[0] == "" ||this.timeList[i].time[1] == "") {
                    this.$Modal.warning({
                        title: "您有必填字段",
                        content: "生效时间不能为空",
                    });
                    return;
                }
            }
            let arr = [];
            this.timeList.forEach((i) => {
                let obj = {
                    startTime: i.time[0],
                    endTime: i.time[1],
                };
                arr.push(obj);
            });
            let o = [];
            this.timeList.forEach((i) => {
                let obj = {
                    startTime: i.time[0],
                    endTime: i.time[1],
                };
                o.push(obj);
            });
            o.map((item) => {
                item.startTime = item.startTime.substring(0, 2) * 60 + item.startTime.substring(3, 5) * 1;
                item.endTime = item.endTime.substring(0, 2) * 60 + item.endTime.substring(3, 5) * 1;
            });
            o.sort((a, b) => {
                return a.startTime - b.startTime;
            });
            for (let i = 1; i < o.length; i++) {
                if (o[i].startTime >= o[i - 1].startTime && o[i].startTime <= o[i - 1].endTime) {
                    this.$Modal.warning({
                        title: "提示",
                        content: "生效时间交叉，请重新选择",
                    });
                    return;
                }
            }
            let params = {
                ruleId: this.timeId,
                timeList: arr,
            };
            getEmpSetTime(params)
                .then((res) => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.timeModal = false;
                        this.getList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
    },
    mounted() {
        this.deptId = this.$store.state.porjectObject.deptId;
        this.btnList = JSON.parse(localStorage.getItem("arr"));
        this.getList();
    },
};
</script>
<style lang="less" scoped>
// @import "./../../assets/style/slider.less";
@import "./../../assets/style/themeBase.less";
.empWarnsetting{
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
    background-color: #f5f5f5;
    /deep/.ivu-tabs{
        padding: 20px;
        background-color: #ffffff;
    }
    .search{
        margin: 10px 0;
    }
}
.tag {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 100%;
    position: relative;
    .msg {
        width: 200px;
        margin-left: 255px;
    }
    .btn {
        width: 150px;
        position: absolute;
        right: 0;
    }
}
.ask {
    width: 100%;
    display: flex;
    height: 30px;
    justify-content: flex-start;
    align-items: center;
    border-radius: 20px;
    border: 1px solid #e5e5e5;
    margin: 0 auto 10px;

    span {
        margin-right: 10px;
        margin-left: 10px;
    }
}
.warn {
    width: 100%;
    margin-top: -20px;
    h2 {
        margin-top: 15px;
        font-size: 14px;
        font-weight: 400;
    }
    .list {
        width: 90%;
        margin: 10px auto 0;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        .item1 {
            margin-left: 10px;
        }
        span {
            padding: 0 5px;
        }
    }
    .box {
        width: 90%;
        margin: 20px auto 0;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        max-height: 300px;
        overflow-y: scroll;
        // .box::-webkit-scrollbar {
        //   display: none;
        // }

        p {
            width: 100px;
            padding: 5px;
            border: 1px dashed #515a6e;
            margin-left: 10px;
            height: 30px;
            border-radius: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
    }
    .box::-webkit-scrollbar {
        // width: 6px;
        display: none;
    }

    // /*滚动槽*/
    // .box::-webkit-scrollbar-track {
    //   -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    //   box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    //   border-radius: 10px;
    // }
    // /* 滚动条滑块 */
    // .box::-webkit-scrollbar-thumb {
    //   border-radius: 10px;
    //   background: rgba(0, 0, 0, 0.1);
    //   -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);
    //   box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);
    // }
    // .box::-webkit-scrollbar-thumb:window-inactive {
    //   background: rgba(255, 0, 0, 0.4);
    // }
}
.ruleBox{
    width: 600px;
    margin:0 auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left{
        width:250px;
        border-right: 1px solid var(--themeColor);
        height: 200px;
    }
    .right{
        width: 350px;
        height: 200px;
        .infoBox{
            .item{
                width: 100%;
                justify-content: space-between;
                align-items: center;
                margin: 0 auto 20px;
                .tip{
                    color: red;
                }
            }
        }
    }
}
.msg{
    width: 100%;
    height: 600px;
    display: flex;
    justify-content: space-between;
    .fence {
        width: calc(100% - 300px);
        height: 100%;
        position: relative;
        #container {
            width: 100%;
            height: 100%;
            // position: relative;
        }
    }
    .right {
        width: 300px;
        height: 100%;
        background: #fff;
        position: relative;
        .top {
            width: 300px;
            height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
            input {
                margin-right: 10px;
                cursor: pointer;
            }
            span {
                margin-right: 30px;
            }
        }
        .isShow {
            width: 200px;
            margin: 0 auto;
        }
        .center {
            width: 280px;
            margin: 0 auto;
            height: 400px;
            overflow-y: scroll;
            p {
                width: 100%;
                height: 50px;
                display: flex;
                justify-content: flex-start;
                align-items: center;
                span {
                    width: 80px;
                    text-align: center;
                    height: 50px;
                    line-height: 50px;
                }
            }
            div {
                width: 100%;
                height: 50px;
                display: flex;
                justify-content: flex-start;
                align-items: center;
            }
        }
        .center::-webkit-scrollbar {
            display: none;
        }
    }
}
.searchAddress{
    width: 300px;
    position: absolute;
    top: 5px;
    left: 300px;
    display: flex;
    justify-content: space-between;
}
#fenceMap {
    height: 100%;
}
/deep/.el-tag.el-tag--error{
    background-color:rgba(255, 72, 72, 0.1);
    border-radius:2px;
    border-color:#FF4848;
    color:#FF4848;
}
/deep/.el-tag.el-tag--success{
    background-color: rgba(63, 207, 119, 0.1);
    border-color:#28D79C;
    color: #3FCF77;
    border-radius:2px;
}
// /deep/.is-disabled{
//         background:#A9B0BB !important;
//         color:#fff !important;
//     }
</style>
